﻿namespace ContactsSync.Infrastructure.Behaviors
{
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Media;

    public class DragAdorner : Adorner
    {
        private readonly ContentPresenter contentPresenter;
        private readonly AdornerLayer adornerLayer;
        private double leftOffset;
        private double topOffset;

        public DragAdorner(object data, DataTemplate dataTemplate, UIElement adornedElement, AdornerLayer adornerLayer)
            : base(adornedElement)
        {
            this.adornerLayer = adornerLayer;
            this.contentPresenter = new ContentPresenter { Content = data, ContentTemplate = dataTemplate, Opacity = 0.75 };

            this.adornerLayer.Add(this);
        }

        protected override int VisualChildrenCount
        {
            get { return 1; }
        }

        public void UpdatePosition(double left, double top)
        {
            this.leftOffset = left;
            this.topOffset = top;

            if (this.adornerLayer != null)
            {
                this.adornerLayer.Update(this.AdornedElement);
            }
        }

        public override GeneralTransform GetDesiredTransform(GeneralTransform transform)
        {
            GeneralTransformGroup result = new GeneralTransformGroup();
            result.Children.Add(base.GetDesiredTransform(transform));
            result.Children.Add(new TranslateTransform(this.leftOffset, this.topOffset));
            return result;
        }

        public void Destroy()
        {
            this.adornerLayer.Remove(this);
        }

        protected override Size MeasureOverride(Size constraint)
        {
            this.contentPresenter.Measure(constraint);
            return this.contentPresenter.DesiredSize;
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            this.contentPresenter.Arrange(new Rect(finalSize));
            return finalSize;
        }

        protected override Visual GetVisualChild(int index)
        {
            return this.contentPresenter;
        }
    }
}